<template>
  <div>
    <Spin :spinning="loading" tip="Loading...">
      <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '10px' }"/>
      <FormPanel
        ref="baseInfo"
        :list="initFormBase"
        :cols="3"
        :labelWidth="140"
        :isSubmitBtn="false"
        :formType="handleType"
      />
      <div v-show="formData.xsddlx == 'Q'">
        <BreakSpace label="特殊追溯订单明细" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
        <FormPanel
          ref="specialOrderForm"
          :list="initSpecialOrderForm"
          :cols="3"
          :labelWidth="140"
          :isSubmitBtn="false"
          :formType="handleType"
        />
      </div>
      <BreakSpace label="配件列表" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
      <FilterTable
        ref="tablePeij"
        columnsRef="yxqPjxmTable"
        height="400"
        selectionType="single"
        :columns="initPjColumn"
        :onCellChange="onPjCellChange"
        :onSyncTableData="syncPjFun"
        :onSummationChange="summationFun"
        :isSelectColumn="false"
        :isMemoryPagination="true"
        isExportExcel2
        :onColumnsChange="columns => (this.initPjColumn = columns)"
        :onRowSelectChange="arr => (this.onChangeColumn = arr)"
      >
        <template slot="controls">
          <el-button v-if="handleType != 'show'" size="small" type="primary" icon="el-icon-plus" @click="openPjDialog">
            添加配件
          </el-button>
          <el-button v-if="handleType != 'show'" size="small" type="primary" icon="el-icon-plus"
                     @click="openimportPjDialog">导入配件
          </el-button>
        </template>
      </FilterTable>
    </Spin>
    <BaseDialog :visible.sync="visbleDealer" title="经销商选择"
                :containerStyle="{ overflow: 'auto', paddingBottom: '60px' }"
                destroyOnClose>
      <add-dealer
        selectionType="single"
        @selectArr="selectDealerFun"
        @closeDialog='visbleDealer = false'></add-dealer>
    </BaseDialog>
    <BaseDialog :visible.sync="visiblePeij" title="配件选择"
                :containerStyle="{ overflow: 'auto', paddingBottom: '60px' }"
                destroyOnClose>
      <add-peij
        selectionType="multiple"
        :params="getPjParams"
        @selectArr="selectPeijianFun"
        @closeDialog='visiblePeij = false'></add-peij>
    </BaseDialog>
    <BaseDialog :visible.sync="visbleVehicle" title="车辆选择"
                :containerStyle="{ overflow: 'auto', paddingBottom: '60px' }"
                destroyOnClose>
      <add-vehicle
        selectionType="single"
        :params="getPjParams"
        @selectArr="selectVehicleFun"
        @closeDialog='visbleVehicle = false'></add-vehicle>
    </BaseDialog>
    <BaseDialog style="min-height: 80vh;" :visible.sync="visibleImportPeij" width="80vw" title="配件导入" destroyOnClose
                :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }"
    >
      <ExcelImport
        ref="import"
        template-file-name="配件导入模板.xlsx"
        :importRules="importRules"
        :onComplete="importComplete"
        @close="visibleImportPeij = false"
      />
    </BaseDialog>
    <div class="dialogBottmView">
      <el-button @click="closeDialogTop">返 回</el-button>
      <el-button v-if="handleType != 'show'" v-show="!loading" @click="saveDialog()" :loading="saveLoading"
                 type="primary">
        保存
      </el-button>
      <el-button
        v-show="!loading"
        v-if="['DLR1','OEM1'].includes(pageType) && handleType !== 'show'"
        :disabled="!(formData.xsddzt == 'C' ||formData.xsddzt == 'TB' ||formData.xsddzt == 'B' || formData.xsddzt == '')"
        @click="saveDialog('T')"
        :loading="saveLoading"
        type="primary">
        保存并提报
      </el-button>
    </div>
  </div>
</template>
<script>
import {dictionary} from '@/utils/dictMixin';
import {
  getOrderPartList,
  getPartOrderById,
  getPartOrderTypeInfo,
  getSalesAgreementList,
  getValidRepeat,
  postSavePartOrder,
  postUpdateStatus,
  putPartOrder
} from '@/api/partsmanage/purchaseManage/purchaseSubmit';
import {getWareHouseByDealerCode} from '@/api/partsmanage/partWarehouseManage/storehouseDealer/index';
import {getDealerAddr} from '@/api/part/accessories';
import {calcDetails, culOrderData, ddlxArr, getPartDetails, mxddztArr} from './constant';
import addDealer from './addDealer';
import addPeij from './addPeij';
import addVehicle from './addVehicle';
import ExcelImport from '@/components/ExcelImport';

const fileFieldArr = ['ddfj', 'xslctp', 'cgfptp', 'jqbzxhqtp', 'jqbzxhhtp', 'djgyhzp', 'djmpzp'];

export default {
  name: 'purchaseSubmitPartOrderDetail',
  components: {
    addDealer,
    addPeij,
    addVehicle,
    ExcelImport
  },
  props: {
    handleType: {
      type: String,
      default: 'add'
    },
    pageType: {
      type: String,
      default: ''
    },
    value: {
      type: Object,
      default: null
    }
  },
  mixins: [dictionary],
  data() {
    return {
      partOrderTypeInfo: '', //类型控制信息
      centralWarehouseInfoY: '', // 中心库信息（油）
      centralWarehouseInfoD: '', // 中心库信息（电）
      formData: {
        dealerCode: '', //经销商code
        dealerName: '', //经销商名称
        xsddzt: '', //订单状态
        xsddsx: '', //油电属性
        xsddlx: '', //订单类型
        bsddid: '', //促销活动
        xsysje: '',
        bsddlx: '1', // 订单提报类型
        receiveAddrId: '', // 详细收货地址
        xxshdz: '', // 详细收货地址
        partCarInfo: {}, //特殊追溯明细
        details: [] //配件订单明细
      },
      loading: false,
      initFormBase: this.initFormBaseFun(),
      initPjColumn: this.initPjColumnFun(),
      initSpecialOrderForm: this.initSpecialOrderFormFun(),
      saveLoading: false,
      visbleDealer: false,
      visiblePeij: false,
      visbleVehicle: false,
      visibleImportPeij: false,
      importRules: this.initImportRuleFun()
    };
  },
  mounted() {
    //判断是新增，还是修改
    this.getSalesAgreementList()
    this.getDdlx()
    if (this.handleType == 'add') {
      if (this.pageType == 'OEM1') { //总部代提报
        this.formData.bsddlx = '2' //提报类型2
      } else {
        this.loading = true;
        Promise.all([
          this.getAddr(),
          this.getWareHouse()
        ]).then(() => {
          this.loading = false;
        })
      }
    } else {
      this.loading = true;
      getPartOrderById(this.value.id).then(res => {
        if (res.resultCode === 200) {
          const data = Object.assign({}, this.formData, this.value.data, res.data);
          this.formData = data;
          this.changeDdlx(this.formData.xsddlx, true);
          Promise.all([
            this.getAddr(),
            this.getWareHouse()
          ]).then(() => {
            this.loading = false;
          })
          this.init();
          this.$nextTick(() => {
            this.$refs.tablePeij.SET_TABLE_DATA(this.culFormData.details);
          });
        }
      })
    }
  },
  computed: {
    getPjParams() {
      return {
        dealerCode: this.formData.dealerCode, // 经销商代码
        xsddlx: this.formData.xsddlx, // 订单类型
        bjpjsx: this.formData.xsddsx, //油电属性
        bsddid: this.formData.bsddid //促销活动id
      }
    },
    culFormData() {
      this.formData.partOrderTypeInfo = this.partOrderTypeInfo;
      return culOrderData(this.formData);
    }
  },
  methods: {
    //获取促销活动下拉框数据
    async getSalesAgreementList() {
      const res = await getSalesAgreementList();
      if (res.resultCode === 200) {
        const bsddidFiled = this.initFormBase.find(i => i.fieldName === 'bsddid')
        bsddidFiled.itemList = res.data.map(i => {
          return {
            text: i.xsxymc,
            value: i.id + ''
          }
        })
      }
    },
    //获取经销商收货地址下拉框 并初始化默认收货地址
    async getAddr() {
      const res = await getDealerAddr({
        dealerCode: this.formData.dealerCode
      });
      if (res.resultCode === 200) {
        const receiveAddrIdFiled = this.initFormBase.find(i => i.fieldName === 'receiveAddrId')
        const itemList = res.data.map(i => {
          if (this.handleType === 'add') {
            if (i.xsdzxz == 50011001) {
              receiveAddrIdFiled.initialValue = i.id + '';
              this.formData.xxshdz = i.xsxxdz;
            }
          }
          return {
            value: i.id + '',
            text: i.xsxxdz
          }
        });
        if (this.handleType !== 'add') {
          if (receiveAddrIdFiled.initialValue && this.formData.receiveAddrId && this.formData.xxshdz) {
            if (!itemList.find(i => i.value == this.formData.receiveAddrId)) {
              itemList.push({
                value: this.formData.receiveAddrId,
                text: this.formData.xxshdz
              });
            }
          }
        }
        receiveAddrIdFiled.itemList = itemList;
      }
    },
    //获取经销商中心库信息
    async getWareHouse() {
      const res = await getWareHouseByDealerCode({
        dealerCode: this.formData.dealerCode
      });
      if (res.resultCode === 200) {
        const datas = res.data
        if (datas.length) {
          this.centralWarehouseInfoY = res.data.find(i => i.bjpjsx == 50001001);
          this.centralWarehouseInfoD = res.data.find(i => i.bjpjsx == 50001002);
        } else {
          if (this.handleType !== 'show') {
            await this.$alert('当前经销商未维护中心库，无法提报订单!', '提示', {
              type: 'error',
              showClose: false,
              showCancelButton: false
            })
            if (this.pageType == 'DLR1') {
              this.closeDialog()
            }
          }
        }
      }
    },
    //修改时，初始化页面数据
    init() {
      //循环为表单赋值
      this.initFormBase.forEach(x => {
        x.initialValue = this.culFormData[x.fieldName];
      });
      //循环为表单赋值
      this.initSpecialOrderForm.forEach(x => {
        if (this.formData.partCarInfo[x.fieldName]) {
          if (fileFieldArr.includes(x.fieldName)) {
            x.initialValue = JSON.parse(this.formData.partCarInfo[x.fieldName]);
          } else {
            x.initialValue = this.formData.partCarInfo[x.fieldName];
          }
        }
      });
    },
    getDdlx(){
      if(this.pageType == 'DLR1') {
        for (var i = 0; i < ddlxArr.length; i++) {
          var item = ddlxArr[i]
          if (item.value === 'M') {
            ddlxArr.splice(i, 1)
          }
        }
      }
      console.info(ddlxArr)
    },
    initImportRuleFun() {
      const appId = localStorage.getItem('appId');
      let pjsxRule = [];
      if (appId == 'beijing') {
        pjsxRule = [
          {
            prop: 'bjpjsx', title: '配件属性',
            rule: [
              {required: true, message: '配件属性不能为空'},
              {itemList: this.createDictList('5000')}
            ]
          },
        ]
      }
      return [
        {
          prop: 'bjxmbh', title: '配件代码',
          rule: [
            {required: true, message: '配件代码不能为空'},
            {
              validator: (callback, rule, val, row, datas) => {
                if (appId == 'arcfox') {
                  row.bjpjsx = 50001002;
                }
                getOrderPartList({
                  ...this.getPjParams,
                  bjxmbh2: val,
                  currentPage: 1,
                  pageSize: 100000,
                }).then(res => {
                  if (res.resultCode === 200) {
                    const datas = res.data.records;
                    if (datas.length) {
                      const pjInfo = datas.find(i => i.bjpjsx == row.bjpjsx)
                      if (pjInfo) {
                        row.partInfo = pjInfo //配件信息
                        callback()
                      } else {
                        callback(new Error(`配件代码${val}和配件属性不匹配`))
                      }
                    } else {
                      callback(new Error(`配件代码${val}不存在或不在当前类型可提报范围内`))
                    }
                  } else {
                    callback(new Error(res.errMsg || '验证失败，请联系管理员'))
                  }
                }).catch(e => {
                  callback(new Error(e || '验证失败，请联系管理员'))
                })
              }
            }
          ]
        },
        ...pjsxRule,
        {
          prop: 'bstxsl', title: '采购数量',
          rule: [
            {required: true, message: '采购数量不能为空'},
            {pattern: /(^[1-9]\d*$)/, message: '请填写正确的采购数量'}
          ]
        }
      ]
    },
    //基本表单信息
    initFormBaseFun() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请选择经销商',
          hidden: (this.pageType == 'DLR1' || this.pageType == 'DLR2'),
          initialValue: '',
          readonly: true,
          disabled: this.handleType != 'add',
          rules: [
            {required: true, trigger: 'change', message: '请选择经销商'}
          ],
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.visbleDealer = true}></el-button>
              </div>
            );
          },
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
          hidden: (this.pageType == 'DLR1' || this.pageType == 'DLR2'),
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '采购单号',
          fieldName: 'xsddhm',
          placeholder: '请输入',
          hidden: this.handleType === 'add',
          initialValue: '',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'xsddlx',
          placeholder: '请选择',
          initialValue: '',
          disabled: this.handleType !== 'add',
          itemList: ddlxArr,
          change: val => {
            this.changeDdlx(val);
          },
          rules: [
            {required: true, message: '请选择订单类型', trigger: 'change'},
          ]
        },
        {
          type: 'SELECT',
          label: '促销活动',
          fieldName: 'bsddid',
          placeholder: '请选择促销活动',
          initialValue: '',
          hidden: true,
          itemList: [],
          change: val => {
            this.changeCxhd(val);
          },
          rules: [
            {required: true, message: '请选择促销活动', trigger: 'change'}
          ]
        },
        {
          type: 'SELECT',
          label: '收货详细地址',
          fieldName: 'receiveAddrId',
          placeholder: '请选择收货详细地址',
          initialValue: '',
          itemList: [],
          selfCols: 3,
          rules: [
            {required: true, message: '请选择收货详细地址', trigger: 'change'}
          ],
          change: val => {
            this.changeAddr(val);
          }
        },
        {
          type: 'INPUT',
          label: '采购总金额',
          fieldName: 'xsysje',
          initialValue: '',
          disabled: true
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'xsddbz',
          placeholder: '请输入',
          rules: [
            {required: false, trigger: 'change'}
          ],
          initialValue: '',
          maxlength: 300,
          selfCols: 3
        },
      ];
    },
    //特殊追溯订单信息
    initSpecialOrderFormFun() {
      const uploadParam = {
        selfCols: 1.5,
        type: 'UPLOAD_IMG',
        placeholder: '上传文件...',
        initialValue: '',
        upload: {
          actionUrl: '/api/file/oss/upload',
          limit: 1,
          fileSize: 20,
          isCalcHeight: true,
          fileTypes: ['jpg', 'jpeg', 'png', 'gif'],
          // tipText: '（支持：jpg、jpeg、png格式）'
        }
      }
      return [
        {
          type: 'INPUT',
          label: '车架号',
          fieldName: 'xsvinm',
          placeholder: '请选择',
          readonly: true,
          initialValue: '',
          rules: [
            {required: true, trigger: 'change', message: '请选择车辆'}
          ],
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.visbleVehicle = true}></el-button>
              </div>
            );
          },
        },
        {
          type: 'INPUT',
          label: '钥匙编号',
          fieldName: 'xsysbh',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'change', message: '请输入钥匙编号'}
          ],
        },
        {
          type: 'INPUT',
          label: '发动机号',
          fieldName: 'xsfdjh',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'change', message: '请输入发动机号'}
          ],
        },
        {
          type: 'INPUT',
          label: '整车型号',
          fieldName: 'xszcxh',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'change', message: '请输入整车型号'}
          ],
        },
        {
          type: 'INPUT',
          label: '发动机最大净功率',
          fieldName: 'xszdgl',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'change', message: '请输入发动机最大净功率'},
            {pattern: /^(-)?(0|[1-9]\d*)(\.\d{1,2})?$/, message: '请输入正确的数值', trigger: 'blur'}

          ],
        },
        {
          type: 'INPUT',
          label: '发动机排量',
          fieldName: 'xszdpl',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'change', message: '请输入发动机排量'},
            // {pattern: /^(-)?(0|[1-9]\d*)(\.\d{1,2})?$/, message: '请输入正确的发动机排量', trigger: 'blur'}
          ],
        },
        {
          type: 'INPUT',
          label: '最大允许总质量',
          fieldName: 'xszdzl',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'change', message: '请输入最大允许总质量'},
            {pattern: /^(-)?(0|[1-9]\d*)(\.\d{1,2})?$/, message: '请输入正确的数值', trigger: 'blur'}
          ],
        },
        {
          type: 'INPUT',
          label: '乘坐人数',
          fieldName: 'xsczrs',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'change', message: '请输入乘坐人数'},
            {pattern: /(^[1-9]\d*$)/, message: '请输入正确的人数', trigger: 'blur'}
          ],
        },
        {
          type: 'INPUT',
          label: '制造年月',
          fieldName: 'xszzny',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'change', message: '请输入制造年月'}
          ],
        },
        {
          type: 'INPUT',
          label: '唯一标识',
          fieldName: 'xswybs',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'change', message: '请输入唯一标识'},
            // {
            //   validator: (rule, value, callback) => {
            //     getValidRepeat({
            //       id: this.formData.partCarInfo.id,
            //       xswybs: value
            //     }).then(res => {
            //       if (res.resultCode == 200) {
            //         res.data ? callback(new Error('唯一标识不能重复')) : callback()
            //       } else {
            //         callback(new Error(res.errMsg || '服务器验证失败'))
            //       }
            //     })
            //   }
            // }
          ],
        },
        {
          type: 'TEXT_AREA',
          label: '订购原因',
          fieldName: 'xsdgyy',
          placeholder: '请输入订购原因',
          initialValue: '',
          rules: [
            {required: false, trigger: 'change', message: '请输入订购原因'}
          ],
          maxlength: 300,
          selfCols: 3
        },
        {
          selfCols: 2,
          type: 'UPLOAD_FILE',
          label: '附件',
          fieldName: 'ddfj',
          initialValue: '',
          upload: {
            fileSize: 20,
            max: 1024 * 20,
            actionUrl: '/api/file/oss/upload'
          },
          rules: [
            {required: true, trigger: 'change', message: '请上传附件'}
          ],
        },
        {
          type: 'INPUT',
          selfCols: 1,
          label: '附件模板',
          fieldName: 'mb',
          hidden: this.handleType == 'show',
          render: () => {
            return (
              <div>
                <a href='/static/template/特殊追溯订单附件模板.xlsx' target='_self'>
                  <el-button icon="el-icon-download">下载附件模板</el-button>
                </a>
              </div>
            );
          },
        },
        {
          ...uploadParam,
          rules: [{required: false, message: '请上传文件', trigger: 'change'}],
          label: '行驶里程图片',
          fieldName: 'xslctp',
        },
        {
          ...uploadParam,
          rules: [{required: false, message: '请上传文件', trigger: 'change'}],
          label: '购车发票图片',
          fieldName: 'cgfptp',
        },
        {
          ...uploadParam,
          rules: [{required: false, message: '请上传文件', trigger: 'change'}],
          label: '旧件标识销毁前图片',
          fieldName: 'jqbzxhqtp',
        },
        {
          ...uploadParam,
          rules: [{required: false, message: '请上传文件', trigger: 'change'}],
          label: '旧件标识销毁后图片',
          fieldName: 'jqbzxhhtp',
        },
        {
          ...uploadParam,
          rules: [{required: false, message: '请上传文件', trigger: 'change'}],
          label: '电机钢印号照片',
          fieldName: 'djgyhzp',
        },
        {
          ...uploadParam,
          rules: [{required: false, message: '请上传文件', trigger: 'change'}],
          label: '电机铭牌照片',
          fieldName: 'djmpzp',
        },
      ];
    },
    //配件列表定义
    initPjColumnFun() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        ...this.handleType == 'show' ? [] : [{
          title: '操作',
          fixed: 'left',
          dataIndex: 'column-action',
          render: props => {
            return (
              <div>
                <el-button disabled={this.handleType === 'show'} size="mini" type="text"
                           onClick={() => this.delPj(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        }],
        {
          title: '厂家发货仓库',
          dataIndex: 'centralWarehouse.bsckmc',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '配件代码',
          dataIndex: 'partInfo.bjxmbh',
          fixed: 'left',
          sorter: true,
          filter: true,
          filterType: 'input',
          formatter(row) {
            if (row.partInfo) {
              return row.bjxmbh || row.partInfo.bjxmbh;
            }
            return row.bjxmbh;
          },
        },
        {
          title: '配件名称',
          dataIndex: 'partInfo.bjzwmc',
          fixed: 'left',
          sorter: true,
          filter: true,
          filterType: 'input',
          formatter(row) {
            if (row.partInfo) {
              return row.bjzwmc || row.partInfo.bjzwmc;
            }
            return row.bjzwmc;
          },
        },
        {
          title: '配件属性',
          dataIndex: 'partInfo.bjpjsx',
          sorter: true,
          dictItems: this.createDictList(5000),
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(5000)
        },
        {
          title: '最小订购量',
          dataIndex: 'bjxszx',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '常规订货价格',
          dataIndex: 'xsxsdj',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '配件折扣',
          dataIndex: 'pjzkl',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            if (!props.row.discounts2.length) {
              return <span>{props.row.pjzkl}</span>
            }
            return (
              <el-popover
                placement="top-start"
                title=""
                width="200"
                trigger="hover"
              >
                {props.row.discounts2.map((i, index) => {
                  if(i.xtlxdm !== 'ZK90') {
                    return (<div>折扣：{i.xtjgjg}{i.xsgzlx == '2' ? '%' : '￥'}</div>)
                  } else {
                    return (<div>无折扣</div>)
                  }
                })}
                <span slot="reference">{props.row.pjzkl}</span>
              </el-popover>
            );
          }
        },
        {
          title: '加收管理费',
          dataIndex: 'jsglfl',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            if (!props.row.discounts2.length) {
              return <span>{props.row.jsglfl}</span>
            }
            return (
              <el-popover
                placement="top-start"
                title=""
                width="200"
                trigger="hover"
              >
                {props.row.discounts2.map((i, index) => {
                  if(i.xtlxdm == 'ZK90') {
                    return (<div>加收：{-Number(i.xtjgjg)}{i.xsgzlx == '2' ? '%' : '￥'}</div>)
                  } else {
                    return (<div>无加收</div>)
                  }
                })}
                <span slot="reference">{props.row.jsglfl}</span>
              </el-popover>
            );
          }
        },
        {
          title: '加价后单价',
          dataIndex: 'jjhdj',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '采购计划数量',
          dataIndex: 'cgjhsl',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '采购数量',
          fixed: 'right',
          dataIndex: 'bstxsl',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: this.handleType != 'show',
          editType: 'number',
          editRequired: true,
          summation: true,
          editValidator: (val, row, callback) => {
            if (Number(val) === 0) {
              return callback(new Error('数量不可以为0'))
            }
            const ys = (Number(val) * 10000000) % (Number(row.bjxszx) * 10000000)
            if (ys > 0) {
              callback(new Error("必须为最小订购量的整数倍"))
            } else {
              callback()
            }
          }
        },
        {
          title: '采购金额（加价后）',
          dataIndex: 'xsysje',
          sorter: true,
          filter: true,
          filterType: 'input',
          summationUnit: '元',
          numberFormat: true,
          summation: true,
          precision: 2
        },
        ...this.handleType != 'show' ? [] : [
          {
            title: 'ERP行号',
            dataIndex: 'bsddhh',
            sorter: true,
          },
          {
            title: '配件状态',
            dataIndex: 'xsddzt',
            sorter: true,
            dictItems: mxddztArr,
          },
          {
            title: '审批数量',
            dataIndex: 'bsspsl',
          },
          {
            title: '分配数量',
            dataIndex: 'bsfpsl',
          },
          {
            title: 'BO数量',
            dataIndex: 'bsbosl',
          },
          {
            title: '取消数量',
            dataIndex: 'qxsl',
          },
          {
            title: '发运数量',
            dataIndex: 'bjfysl',
          },
          {
            title: '签收数量',
            dataIndex: 'bjddsl',
          },
          {
            title: '实收数量',
            dataIndex: 'pjrksl',
          },
          {
            title: '已开票数量',
            dataIndex: 'pjkpsl',
          },
          {
            title: '开票金额',
            dataIndex: 'pjkpje',
          },
        ],
      ];
    },
    //订单类型切换
    changeDdlx(xsddlx, initFlg) {
      // if (initFlg) { //初始化直接切换
      return this.handleChangeDdlx(xsddlx, initFlg)
      // }
      if (this.formData.details.length) {
        this.$confirm('切换订单类型将导致配件明细被清空，你确定吗？')
          .then(r => {
            this.handleChangeDdlx(xsddlx, initFlg)
          }).catch(e => {
          this.initFormBase.find(i => i.fieldName === 'xsddlx').initialValue = this.formData.xsddlx
        })
      } else {
        this.handleChangeDdlx(xsddlx, initFlg)
      }
    },
    handleChangeDdlx(xsddlx, initFlg) {
      if (!initFlg) {
        this.formData.xsddsx = ''
        this.$refs.tablePeij.SET_TABLE_DATA([]) //改变类型就清空配件明细
      }
      //只有常规订单才显示采购计划数量
      this.initPjColumn.find(i => i.dataIndex === 'cgjhsl').hidden = xsddlx !== 'S'
      //促销和免费出库订单需要选择活动
      this.$nextTick(() => {
        this.initFormBase.find(i => i.fieldName === 'bsddid').hidden = !(xsddlx === 'P')
      })
      this.formData.xsddlx = xsddlx
      this.getPartOrderTypeInfo()
    },
    /*获取配件订单类型控制信息*/
    getPartOrderTypeInfo() {
      if (this.formData.xsddlx) {
        this.loading = true;
        getPartOrderTypeInfo({
          xsddlx: this.formData.xsddlx,
          dealerCode: this.formData.dealerCode
        }).then(res => {
          if (res.resultCode === 200) {
            this.loading = false;
            this.partOrderTypeInfo = res.data
          }
        })
      }
    },
    //选择促销活动
    changeCxhd(bsddid) {
      this.formData.bsddid = bsddid
    },
    //收货地址切换
    changeAddr(addr) {
      if (addr) {
        const receiveAddrIdFiled = this.initFormBase.find(i => i.fieldName === 'receiveAddrId')
        const addrItem = receiveAddrIdFiled.itemList.find(i => i.value == addr);
        this.formData.xxshdz = addrItem.text;
      } else {
        this.formData.xxshdz = '';
      }
    },
    /* 添加配件明细之前的验证 */
    validForm() {
      if (this.formData.bsddlx == '2') {
        if (!this.formData.dealerCode) {
          this.$notify.error({title: '提示信息', message: '请先选择经销商!'});
          return false
        }
      }
      if (!this.formData.xsddlx) {
        this.$notify.error({title: '提示信息', message: '请先选择订单类型!'});
      } else {
        if (this.formData.xsddlx === 'Q') { //特殊追溯需要先选择车辆信息
          if (this.formData.partCarInfo.xsvinm) {
            return true
          } else {
            this.$notify.error({title: '提示信息', message: '请先选择车辆信息!'});
          }
        } else if (this.formData.xsddlx === 'P') {
          //活动订单需要先选择活动
          if (this.formData.bsddid) {
            return true
          } else {
            this.$notify.error({title: '提示信息', message: '请先选择活动信息!'});
          }
        } else {
          return true
        }
      }
    },
    /* 打开添加配件Dialog */
    openPjDialog() {
      if (this.validForm()) {
        this.visiblePeij = true;
      }
    },
    /* 打开导入配件Dialog */
    openimportPjDialog() {
      if (this.validForm()) {
        this.visibleImportPeij = true;
      }
    },
    validDetails(datas) {
      //如果是特殊追溯订单，则只能提报单种配件
      if (this.formData.xsddlx == 'Q') {
        if ((this.formData.details.length + datas.length) > 1) {
          const msg = ddlxArr.find(i => i.value == 'Q').text + '只能提报单种配件！';
          this.$notify.error({title: '提示信息', message: msg});
          return msg;
        }
      }
      //判断中心库是否维护
      const partInfos = datas.map(i => i.partInfo || i);
      const hasY = partInfos.some(i => i.bjpjsx == 50001001);
      const hasD = partInfos.some(i => i.bjpjsx == 50001002);
      if (hasY && !this.centralWarehouseInfoY) {
        const msg = '经销商未维护油属性中心库，无法提报油属性配件！';
        this.$notify.error({title: '提示信息', message: msg});
        return msg;
      }
      if (hasD && !this.centralWarehouseInfoD) {
        const msg = '经销商未维护电属性中心库，无法提报电属性配件！';
        this.$notify.error({title: '提示信息', message: msg});
        return msg;
      }
    },
    //导入
    importComplete(datas, callback) {
      const errorData = []
      datas.forEach((item, index1) => {
        const indexarr = []
        datas.forEach((i, index2) => {
          if (i.partInfo.id === item.partInfo.id && index1 !== index2) {
            indexarr.push(index2 + 1)
          }
        });
        if (indexarr.length) {
          errorData.push({
            rownum: index1 + 1,
            errormsg: `配件信息和${indexarr.join(',')}行重复`
          });
        }
      })
      if (errorData.length) { //有错误
        callback(errorData);
      } else {
        const msg = this.validDetails(datas);
        if (msg) {
          return callback([{
            errormsg: msg
          }]);
        }
        callback(); //完成
        this.addPartDetails(datas);
        this.visibleImportPeij = false;
      }
    },
    /*选择配件回调 */
    selectPeijianFun(arr) {
      const msg = this.validDetails(arr);
      if (msg) return;
      this.visiblePeij = false
      const details = arr.map(partInfo => {
        return {
          partInfo,
          bstxsl: partInfo.bjcgzx
        }
      })
      this.addPartDetails(details);
    },
    /*添加配件明细行*/
    addPartDetails(details) {
      const addArr = getPartDetails({
        details: details.filter(i => !this.formData.details.some(j => j.partInfoId === i.partInfo.id)),
        centralWarehouseInfoY: this.centralWarehouseInfoY,
        centralWarehouseInfoD: this.centralWarehouseInfoD,
        partOrderTypeInfo: this.partOrderTypeInfo
      }, this.formData.isJsY, this.formData.isJsD);
      this.$refs.tablePeij.EXECUTE_INSERT(addArr);
    },
    /*选择经销商信息回调 */
    selectDealerFun(arr) {
      const dealer = arr[0]
      this.visbleDealer = false;
      this.formData.dealerCode = dealer.dealerCode;
      this.formData.dealerName = dealer.dealerName;
      this.formData.xxshdz = dealer.xxshdz;
      this.initFormBase.find(i => i.fieldName == 'dealerCode').initialValue = this.formData.dealerCode;
      this.initFormBase.find(i => i.fieldName == 'dealerName').initialValue = this.formData.dealerName;
      this.initFormBase.find(i => i.fieldName == 'receiveAddrId').initialValue = '';
      this.getAddr();
      this.getWareHouse();
      this.getPartOrderTypeInfo();
    },
    /*选择车辆信息回调 */
    selectVehicleFun(arr) {
      const vehicle = arr[0]
      this.visbleVehicle = false
      this.formData.partCarInfo.vehicleId = vehicle.id
      this.formData.partCarInfo.xsvinm = vehicle.vin
      this.formData.partCarInfo.xsysbh = vehicle.keyNumber
      this.formData.partCarInfo.xsfdjh = vehicle.engineNo
      this.formData.partCarInfo.xszcxh = ''
      this.formData.partCarInfo.xszdgl = ''
      this.formData.partCarInfo.xszdpl = vehicle.engineDesc
      this.formData.partCarInfo.xszdzl = ''
      this.formData.partCarInfo.xsczrs = ''
      this.formData.partCarInfo.xszzny = vehicle.productDate

      if (vehicle.powerType == 60081001) { //燃油
        this.formData.xsddsx = 50001001
      } else if (vehicle.powerType == 60081002) { //新能源
        this.formData.xsddsx = 50001002
      }

      //循环为表单赋值
      this.initSpecialOrderForm.forEach(x => {
        if (this.formData.partCarInfo[x.fieldName]) {
          x.initialValue = this.formData.partCarInfo[x.fieldName];
        }
      });
    },
    // // 配件采购数量改变计算
    onPjCellChange(e, row) {
      calcDetails(row)
    },
    delPj(row) {
      this.$refs.tablePeij.EXECUTE_DELETE([row])
    },
    // 配件列表明细数据获取
    syncPjFun(details) {
      this.formData.details = details;
      //特殊追溯订单 配件类别不同，必填项不同
      if (this.formData.xsddlx != 'Q') return;
      let fieldArr = [];
      if (details.length) {
        const partInfo = details[0].partInfo;
        if (partInfo.bjpjfl == 50171001) { //钥匙类
          fieldArr = ['xsysbh'];
        } else if (partInfo.bjpjfl == 50171002) { //发动机类
          fieldArr = ['xsfdjh', 'xslctp', 'cgfptp', 'jqbzxhqtp', 'jqbzxhhtp'];
        } else if (partInfo.bjpjfl == 50171003) { //铭牌
          fieldArr = ['xsvinm', 'xszcxh', 'xszdgl', 'xszdpl', 'xszdzl', 'xsczrs', 'xszzny', 'jqbzxhqtp', 'jqbzxhhtp'];
        } else if (partInfo.bjpjfl == 50171004) { //车身
          fieldArr = ['xsvinm', 'jqbzxhqtp', 'jqbzxhhtp'];
        } else if (partInfo.bjpjfl == 50171005) { //驱动电机
          fieldArr = ['xsvinm', 'djgyhzp', 'djmpzp'];
        }
      }
      fieldArr.push(...['xsvinm', 'xswybs', 'xsdgyy', 'ddfj']);
      this.initSpecialOrderForm.forEach(i => {
        if (i.rules) {
          i.rules[0].required = fieldArr.includes(i.fieldName);
        }
      })
    },
    // 合计值获取
    summationFun(summary) {
      summary.forEach(i => {
        if (i.dataIndex == 'xsysje') {
          this.formData.xsysje = i.value;
          this.initFormBase.find(i => i.fieldName == 'xsysje').initialValue = i.value;
        }
      })
    },
    //保存
    async saveDialog(xsddzt = 'C') {
      this.saveLoading = true;
      try {
        if (this.handleType == 'show' && xsddzt === 'T') {
          return this.tbHandle()
        }
        let [err, data] = await this.$refs.baseInfo.GET_FORM_DATA();
        if (this.formData.xsddlx == 'Q') {
          const [err2, data2] = await this.$refs.specialOrderForm.GET_FORM_DATA();
          if (!err2) {
            this.formData.partCarInfo = Object.assign({}, this.formData.partCarInfo, data2);
            const partCarInfo = this.formData.partCarInfo;
            fileFieldArr.forEach(fieldName => {
              partCarInfo[fieldName] = JSON.stringify(partCarInfo[fieldName])
            });
          }
          err = err || err2;
        }
        const err3 = this.$refs.tablePeij.GET_REQUIRED_ERROR();
        const err4 = this.$refs.tablePeij.GET_FORMAT_ERROR();
        if (err || err3 || err4) {
        } else {
          this.formData = Object.assign({}, this.formData, data);
          const formData = {
            ...this.culFormData,
            xsddzt
          };
          if (!formData.details.length) {
            throw new Error('配件订单明细不能为空！');
          } else {
            if (this.partOrderTypeInfo) {
              if (xsddzt == 'T' && formData.xsysje < this.partOrderTypeInfo.pjlxje) {
                throw new Error(`不满足订单最低提报金额！（${this.partOrderTypeInfo.pjlxje}元）`);
              }
            }
            if (this.validDetails([])) throw new Error();
          }
          let res;
          if (this.handleType === "add") { // 新增
            res = await postSavePartOrder(formData);
          } else { // 修改
            res = await putPartOrder(formData);
          }
          if (res.resultCode === 200) {
            if (res.data) {
              this.$notify.warning({title: '提示信息', message: res.data});
            } else {
              this.$notify.success({title: '提示信息', message: (xsddzt == 'T' ? '提报成功' : '保存成功!')});
            }
            // 重新加载
            this.closeDialog('refresh');
          } else {
            // this.$notify.error({title: '提示信息', message: res.errMsg || '保存失败!'});
          }
        }
      } catch (e) {
        this.saveLoading = false;
        if (e.message) return this.$notify.error({title: '提示信息', message: e.message});
      }
      this.saveLoading = false;
    },
    // 提报
    async tbHandle() {
      this.saveLoading = true
      const res = await postUpdateStatus({
        id: this.formData.id,
        xsddzt: 'T'
      })
      if (res.resultCode == 200) {
        if (res.data) {
          this.$notify.warning({title: '提示信息', message: res.data});
        } else {
          this.$notify.success({title: '提示信息', message: '提报成功'});
        }
        this.closeDialog('refresh');
      }
      this.saveLoading = false
    },
    closeDialogTop() {
      return this.closeDialog('closeDialog');
      this.$confirm('确认关闭窗口吗？您所做的操作将不会被保存！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
        })
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', type);
    }
  }
};
</script>

<style lang="less" scoped>
</style>
